<template>
  <el-drawer
    :title="drawerTitle"
    :visible.sync="drawerVisible"
    :before-close="handleClose"
    direction="rtl"
    size="80%"
    :modal="true"
    :wrapper-closable="false"
    append-to-body
    custom-class="ticket-comment-drawer"
    @opened="handleDrawerOpened"
  >
    <div class="ticket-detail-container">
      <!-- 工单详情头部 - 简化为单行 -->
      <div class="ticket-info">
        <div class="ticket-header">
          <div class="ticket-actions">
            <el-select
              v-if="ticketDetail.id"
              v-model="ticketDetail.status"
              size="mini"
              placeholder="状态"
              class="status-select"
              :class="ticketDetail.status + '-status'"
              @change="handleStatusChange"
            >
              <el-option
                v-for="item in statusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
                <span :style="{ color: getStatusColor(item.value) }">{{ item.label }}</span>
              </el-option>
            </el-select>
            <el-tag v-if="ticketDetail.id" :type="priorityTypeMap[ticketDetail.priority]" size="mini" style="margin-left: 5px">
              {{ ticketDetail.priority === 0 ? '低' : (ticketDetail.priority === 1 ? '中' : '高') }}
            </el-tag>
            <span v-if="ticketDetail.id" class="ticket-meta-item">负责人: {{ ticketDetail.assignee_name || '未分配' }}</span>

            <!-- 添加截止时间显示和修改功能 -->
            <span v-if="ticketDetail.id" class="ticket-meta-item">
              截止时间: {{ ticketDetail.end_at ? formatDateTime(ticketDetail.end_at) : '未设置' }}
              <el-tooltip content="修改截止时间" placement="top">
                <i class="el-icon-time set-deadline-icon" @click="openDeadlineDialog" />
              </el-tooltip>
            </span>

            <!-- 工单转发按钮 -->
            <el-button
              v-if="ticketDetail.id && canForwardTicket"
              type="text"
              size="mini"
              icon="el-icon-share"
              class="forward-ticket-btn"
              @click="openForwardDialog"
            >转发工单</el-button>

            <!-- 添加历史工单按钮，当有多个工单时显示 -->
            <el-button
              v-if="tickets.length > 1"
              type="text"
              size="mini"
              class="history-tickets-btn"
              @click="historyTicketsVisible = true"
            >
              历史工单 ({{ tickets.length }})
            </el-button>

            <!-- 创建新工单按钮 -->
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-plus"
              class="create-ticket-btn"
              @click="openCreateTicketForm"
            >创建新工单</el-button>
          </div>
        </div>
      </div>

      <!-- 评论部分 -->
      <div class="ticket-comments-container">
        <div class="comment-controls">
          <span class="comment-count">{{ comments.length }} 条信息</span>
          <el-dropdown trigger="click" size="mini" @command="changeCommentSortOrder">
            <span class="el-dropdown-link">
              {{ commentSortOrder === 'newest-first' ? '最新在前' : '最早在前' }} <i class="el-icon-arrow-down el-icon--right" />
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="newest-first">最新在前</el-dropdown-item>
              <el-dropdown-item command="oldest-first">最早在前</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
        <div v-loading="loadingComments" class="comment-list" element-loading-text="加载评论中...">
          <div v-for="(comment, index) in sortedComments" :key="comment.id || index" class="comment-item" :class="{'system-comment': !comment.creator_name}">
            <div class="comment-header">
              <span class="comment-author">{{ comment.creator_name || '系统' }}</span>
              <span class="comment-time">{{ comment.create_at_short || comment.create_at }}</span>
            </div>
            <div class="comment-content" v-html="comment.content" />

            <!-- 文件展示 -->
            <div v-if="comment.crmfiles && comment.crmfiles.length > 0" class="file-list">
              <div v-for="item in comment.crmfiles" :key="item.id" class="file-item">
                <el-image
                  v-if="item.content_type && item.content_type.indexOf('image') !== -1"
                  :src="item.url"
                  :preview-src-list="[item.url]"
                  class="file-icon"
                />
                <a v-else :href="item.url" target="_blank" :title="'点击下载' + item.filename" @click.prevent="downloadFile(item)">
                  <svg-icon
                    v-if="item.filename && item.filename.indexOf('pdf') !== -1"
                    icon-class="pdf"
                    class="file-icon"
                  />
                  <svg-icon
                    v-else-if="item.filename && item.filename.indexOf('xlsx') !== -1"
                    icon-class="xlsx"
                    class="file-icon"
                  />
                  <svg-icon
                    v-else-if="item.filename && item.filename.indexOf('xls') !== -1"
                    icon-class="xls"
                    class="file-icon"
                  />
                  <svg-icon
                    v-else-if="item.filename && item.filename.indexOf('zip') !== -1"
                    icon-class="zip"
                    class="file-icon"
                  />
                  <svg-icon
                    v-else
                    icon-class="document"
                    class="file-icon"
                  />
                </a>
                <div class="file-name">
                  <a :href="item.url" target="_blank" title="点击下载">{{ item.filename }}</a>
                </div>
              </div>
            </div>
          </div>
          <div v-if="!comments.length && !loadingComments" class="no-comments">
            <i class="el-icon-chat-dot-square" />
            <p>暂无评论</p>
          </div>
        </div>

        <div v-if="!readonly" class="comment-form">
          <el-form ref="commentForm" :model="commentForm" size="small">
            <!-- 文件附件 -->
            <el-form-item label="附件" class="compact-form-item attachment-form-item">
              <div class="attachment-content">
                <!-- 上传按钮 -->
                <div class="upload-button-container">
                  <crmfilequickuploader :default-expanded="false" icon-only @insert="handleInsertFile" />
                </div>

                <!-- 展示已选择的文件 -->
                <div v-if="commentForm.crmfiles && commentForm.crmfiles.length > 0" class="file-list-compact">
                  <div v-for="(item, index) in commentForm.crmfiles" :key="index" class="file-item-compact">
                    <span class="file-name-compact">{{ item.filename }}</span>
                    <i class="el-icon-close" @click="removeFile(index)" />
                  </div>
                </div>
              </div>
            </el-form-item>

            <el-form-item prop="content" :rules="{ required: true, message: '请输入评论内容', trigger: 'blur' }" class="compact-form-item">
              <div id="editorContainer">
                <tiptap-editor
                  ref="editor"
                  v-model="commentForm.content"
                  :height="120"
                  :auto-focus="true"
                />
              </div>
            </el-form-item>

            <el-form-item class="compact-form-item">
              <div class="form-actions">
                <el-button type="primary" size="small" icon="el-icon-refresh" @click="handleRefreshComments">刷新</el-button>
                <el-button type="primary" size="small" :loading="submitting" @click="submitComment">提交</el-button>
              </div>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>

    <!-- 工单创建/编辑表单 -->
    <crm-ticket-form
      :visible.sync="ticketFormVisible"
      status="create"
      :default-order-id="orderId"
      @close="ticketFormVisible = false"
      @success="handleTicketCreated"
    />

    <!-- 历史工单选择对话框 -->
    <el-dialog
      title="历史工单列表"
      :visible.sync="historyTicketsVisible"
      width="50%"
      append-to-body
    >
      <el-table :data="tickets" style="width: 100%">
        <el-table-column prop="id" label="工单ID" width="80" />
        <el-table-column prop="name" label="工单名称" />
        <el-table-column prop="status_display" label="状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="statusTypeMap[scope.row.status]" size="mini">{{ scope.row.status_display }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="create_at" label="创建时间" width="180" />
        <el-table-column label="操作" width="120" fixed="right">
          <template slot-scope="scope">
            <el-tag
              v-if="scope.row.id === ticketDetail.id"
              type="success"
              size="mini"
              style="margin-right: 5px"
            >当前</el-tag>
            <el-button
              v-else
              type="primary"
              size="mini"
              @click="loadTicketData(scope.row.id); historyTicketsVisible = false;"
            >查看</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="historyTicketsVisible = false">关闭</el-button>
        <el-button type="primary" size="small" @click="openCreateTicketForm">创建新工单</el-button>
      </div>
    </el-dialog>

    <!-- 截止时间修改对话框 -->
    <el-dialog
      title="修改截止时间"
      :visible.sync="deadlineDialogVisible"
      width="30%"
      append-to-body
    >
      <el-form :model="deadlineForm" label-width="100px">
        <el-form-item label="截止时间">
          <el-date-picker
            v-model="deadlineForm.end_at"
            type="datetime"
            placeholder="选择截止时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="deadlineDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submittingDeadline" @click="updateDeadline">确认</el-button>
      </div>
    </el-dialog>

    <!-- 工单转发对话框 -->
    <el-dialog
      title="转发工单"
      :visible.sync="forwardDialogVisible"
      width="40%"
      append-to-body
    >
      <div class="forward-info">
        <p><strong>工单名称：</strong>{{ ticketDetail.name }}</p>
        <p><strong>当前负责人：</strong>{{ ticketDetail.assignee_name || '未分配' }}</p>
      </div>
      <el-form :model="forwardForm" label-width="120px">
        <el-form-item label="转发给" required>
          <el-select
            v-model="forwardForm.assignee_id"
            placeholder="请选择新的负责人"
            filterable
            remote
            reserve-keyword
            :remote-method="remoteSearchUsers"
            :loading="usersLoading"
            style="width: 100%"
            @focus="getUsersList"
          >
            <el-option
              v-for="user in usersList"
              :key="user.id"
              :label="user.show_name || user.name"
              :value="user.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="转发说明">
          <el-input
            v-model="forwardForm.note"
            type="textarea"
            :rows="3"
            placeholder="请输入转发说明（可选）"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="forwardDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submittingForward" @click="confirmForward">确认转发</el-button>
      </div>
    </el-dialog>
  </el-drawer>
</template>

<script>
import { Get, GetComment, PostComment, Put, GetStatusOptions } from '@/api/crm/ticket'
import { CRMGetProjectUsers as GetUsers } from '@/api/crm/crmmanage'
import Crmfilequickuploader from '@/components/crmfilequickuploader'
import CrmTicketForm from './crmticketform'
import TiptapEditor from '@/components/Tiptap'

export default {
  name: 'CrmTicketComments',
  components: {
    Crmfilequickuploader,
    CrmTicketForm,
    TiptapEditor
  },
  props: {
    // 工单ID，与订单ID二选一传入
    ticketId: {
      type: [Number, String],
      default: null
    },
    // 订单ID，与工单ID二选一传入
    orderId: {
      type: [Number, String],
      default: null
    },
    // 是否只读模式（不显示评论表单）
    readonly: {
      type: Boolean,
      default: false
    },
    // 控制抽屉是否显示
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      drawerVisible: false,
      drawerTitle: '工单评论',
      ticketDetail: {}, // 工单详情
      comments: [],
      commentForm: {
        content: '',
        ticket_id: null,
        order_id: null,
        crmfiles: []
      },
      fileList: [],
      loading: false,
      loadingComments: false,
      submitting: false,
      ticketFormVisible: false,
      tickets: [], // 存储工单列表
      historyTicketsVisible: false, // 控制历史工单对话框显示
      internalTicketId: null, // 内部使用的工单ID，避免直接修改prop

      // 状态选项
      statusOptions: [
        { value: 'open', label: '开启' },
        { value: 'hold', label: '暂停' },
        { value: 'close', label: '关闭' }
      ],

      // 状态和优先级映射
      statusTypeMap: {
        'open': 'success',
        'hold': 'warning',
        'close': 'info'
      },
      priorityTypeMap: {
        0: 'info',
        1: 'warning',
        2: 'danger'
      },

      // 评论排序方式：newest-first 或 oldest-first
      commentSortOrder: 'newest-first',

      // 组件数据加载标记，避免重复加载
      dataLoaded: false,

      // 截止时间相关
      deadlineDialogVisible: false,
      deadlineForm: {
        end_at: null
      },
      submittingDeadline: false,

      // 工单转发相关
      forwardDialogVisible: false,
      forwardForm: {
        assignee_id: null,
        note: ''
      },
      submittingForward: false,
      usersList: [], // 员工列表
      usersLoading: false // 用户加载状态
    }
  },
  computed: {
    // 排序后的评论列表
    sortedComments() {
      if (!this.comments || !this.comments.length) return []

      // 创建一个新数组进行排序，避免修改原数组
      const sorted = [...this.comments]

      if (this.commentSortOrder === 'newest-first') {
        // 按时间降序排列，最新的在前面
        return sorted.sort((a, b) => {
          return new Date(b.create_at) - new Date(a.create_at)
        })
      } else {
        // 按时间升序排列，最早的在前面
        return sorted.sort((a, b) => {
          return new Date(a.create_at) - new Date(b.create_at)
        })
      }
    },

    // 判断是否可以转发工单
    canForwardTicket() {
      if (!this.ticketDetail || !this.ticketDetail.id) return false

      // 获取当前用户信息
      const currentUser = this.$store.getters.name
      const currentUserId = this.$store.getters.userId

      // 判断当前用户是否是工单负责人或发起人
      return (
        this.ticketDetail.assignee_id === currentUserId ||
        this.ticketDetail.creator_id === currentUserId ||
        this.ticketDetail.assignee_name === currentUser ||
        this.ticketDetail.creator_name === currentUser
      )
    }
  },
  watch: {
    visible: {
      handler(val) {
        this.drawerVisible = val
        if (val) {
          // 抽屉打开时清空表单
          this.$nextTick(() => {
            this.clearForm()
          })
        } else {
          // 抽屉关闭时，清空表单和数据
          this.clearData()
        }
      },
      immediate: true
    },
    drawerVisible: {
      handler(val) {
        this.$emit('update:visible', val)
      }
    },
    ticketId: {
      handler(val) {
        // 当prop值变化时，更新内部状态
        this.internalTicketId = val
        // 只在 ticketId 变化且抽屉可见时加载数据
        if (val && this.drawerVisible) {
          this.loadTicketData(val)
        }
      },
      immediate: true
    },
    orderId: {
      handler(val) {
        // 只在 orderId 变化且抽屉可见时加载数据
        // 但不在组件初始化时调用，避免与handleDrawerOpened重复调用
        if (val && this.drawerVisible && this.dataLoaded) {
          // 清空所有ticket相关的数据
          this.ticketDetail = {}
          this.internalTicketId = null
          this.commentForm.ticket_id = null
          // 然后加载新order的评论
          this.loadOrderComments(val)
        }
        // 标记组件已初始化完成，后续orderId变化时才会触发加载
        this.dataLoaded = true
      },
      immediate: true
    },
    ticketFormVisible: {
      handler(val) {
        if (!val && this.drawerVisible) {
          // If the form is closed but the main drawer is still open,
          // maybe reload comments or take other actions?
          // Currently, it just reflects the state.
        }
      }
    }
  },
  methods: {
    // 移除文件
    removeFile(index) {
      this.commentForm.crmfiles.splice(index, 1)
    },

    // 清空数据
    clearData() {
      this.clearForm()
      this.comments = []
      this.ticketDetail = {}
      this.tickets = [] // 清空工单列表

      // 重置转发相关状态
      this.forwardDialogVisible = false
      this.forwardForm = {
        assignee_id: null,
        note: ''
      }
      this.usersList = []
      this.usersLoading = false
    },

    // 关闭抽屉
    handleClose() {
      this.drawerVisible = false
      this.$emit('close')
    },

    // 获取工单状态选项
    getStatusOptions() {
      GetStatusOptions().then(response => {
        if (response.data && response.data.length > 0) {
          this.statusOptions = response.data
        }
      }).catch(error => {
        console.error('获取状态选项失败:', error)
      })
    },

    // 抽屉打开完成事件
    handleDrawerOpened() {
      // 抽屉打开完成后加载数据
      // 先清空旧数据
      this.ticketDetail = {}
      this.comments = []
      this.internalTicketId = null // 确保清空内部工单ID
      this.commentForm.ticket_id = null // 确保清空表单中的ticket_id

      // 设置加载中的标题
      this.drawerTitle = this.ticketId ? '工单加载中...' : '订单评论加载中...'

      // 获取状态选项
      this.getStatusOptions()

      // Reset ticket form visibility
      this.ticketFormVisible = false

      // 加载工单数据和评论
      const loadPromise = this.ticketId
        ? this.loadTicketData(this.ticketId)
        : (this.orderId ? this.loadOrderComments(this.orderId) : Promise.resolve())

      loadPromise.finally(() => {
        // 更新标题，移除加载状态
        if (this.ticketDetail && this.ticketDetail.name) {
          this.drawerTitle = `工单: ${this.ticketDetail.name}`
        } else if (this.orderId) {
          this.drawerTitle = '订单评论'
        } else {
          this.drawerTitle = '评论'
        }
      })
    },

    // 加载工单数据和评论
    loadTicketData(id) {
      if (!id) return Promise.resolve()

      this.commentForm.ticket_id = id
      // 不要清空orderId，确保能够保持工单列表
      // this.commentForm.order_id = null
      this.internalTicketId = id // 记录当前选中的工单ID，防止后续被重置

      // 关闭截止时间对话框
      this.deadlineDialogVisible = false

      // 先获取工单详情
      return Get(id)
        .then(response => {
          this.ticketDetail = response.data

          // 更新标题显示工单名称
          this.drawerTitle = `工单: ${this.ticketDetail.name || ''}`

          // 然后获取评论列表
          return this.fetchComments()
        })
        .catch(error => {
          console.error('获取工单详情失败:', error)
          this.$notify({
            title: '错误',
            message: '获取工单详情失败',
            type: 'error',
            duration: 2000
          })
          this.drawerTitle = '工单评论 (加载失败)'
          return Promise.reject(error)
        })
    },

    // 加载订单评论
    loadOrderComments(id) {
      if (!id) return Promise.resolve()

      this.loadingComments = true
      this.commentForm.order_id = id
      this.commentForm.ticket_id = null
      this.internalTicketId = null // 清空当前选中的工单ID
      this.ticketDetail = {} // 清空当前工单详情
      this.drawerTitle = '订单评论'

      // 获取评论列表
      return this.fetchComments()
        .catch(error => {
          console.error('获取订单评论失败:', error)
          this.$notify({
            title: '提示',
            message: '未找到该订单关联的工单，您可以创建一个新工单。',
            type: 'info',
            duration: 3000
          })
          return Promise.reject(error)
        })
        .finally(() => {
          this.loadingComments = false
        })
    },

    // 获取评论列表 - 修改为处理工单列表
    fetchComments() {
      this.loadingComments = true

      const params = new URLSearchParams()

      // 只有在ticketId有效且不为空字符串时才添加ticket_id参数
      if (this.internalTicketId && String(this.internalTicketId).trim() !== '') {
        params.append('ticket_id', this.internalTicketId)
      }

      // 如果有order_id，始终附加它以获取完整工单列表
      if (this.orderId) {
        params.append('order_id', this.orderId)

        // 确保在通过orderId查询时不会同时传递ticket_id参数
        if (!this.internalTicketId) {
          // 双重检查，确保commentForm.ticket_id也被清空
          this.commentForm.ticket_id = null
        }
      }

      if (!this.internalTicketId && !this.orderId) {
        this.loadingComments = false
        return Promise.resolve()
      }

      // 打印请求参数以便调试
      console.log('请求参数:', params.toString(), '当前ticketId:', this.internalTicketId, '当前orderId:', this.orderId)

      return GetComment(null, params.toString())
        .then(response => {
          // 处理工单列表和评论数据
          if (response.data.tickets) {
            this.tickets = response.data.tickets || []

            // 如果tickets为空且不是通过ticketId查询，清空工单详情
            if (this.tickets.length === 0 && !this.internalTicketId) {
              this.ticketDetail = {}
              this.commentForm.ticket_id = null
              this.drawerTitle = '订单评论'
            } else if (this.tickets.length > 0 && !this.internalTicketId) {
              // 如果有工单，且没有指定工单ID，则设置当前工单详情为第一个工单
              this.ticketDetail = this.tickets[0] // 假设返回的第一个工单是最新的
              this.commentForm.ticket_id = this.ticketDetail.id
              this.internalTicketId = this.ticketDetail.id

              // 更新标题显示工单名称
              this.drawerTitle = `工单: ${this.ticketDetail.name || ''}`
            } else if (this.tickets.length > 0 && this.internalTicketId) {
              // 如果指定了ticketId，确保当前工单详情为选定的工单
              const selectedTicket = this.tickets.find(ticket => ticket.id === this.internalTicketId)
              if (selectedTicket) {
                this.ticketDetail = selectedTicket
              }
            }
          } else {
            // 如果没有返回tickets字段，清空工单列表
            this.tickets = []
            if (!this.internalTicketId) {
              this.ticketDetail = {}
              this.commentForm.ticket_id = null
            }
          }

          this.comments = response.data.data || []

          // 更新标题显示
          if (this.ticketDetail.id && this.ticketDetail.name) {
            if (this.tickets.length > 1) {
              this.drawerTitle = `工单: ${this.ticketDetail.name || ''} (有${this.tickets.length}个历史工单)`
            } else {
              this.drawerTitle = `工单: ${this.ticketDetail.name}`
            }
          } else if (this.orderId) {
            this.drawerTitle = '订单评论'
          }

          return this.comments
        })
        .catch(error => {
          console.error('获取评论列表失败:', error)
          this.$notify({
            title: '错误',
            message: '获取评论列表失败',
            type: 'error',
            duration: 2000
          })
          return Promise.reject(error)
        })
        .finally(() => {
          this.loadingComments = false
        })
    },

    // 从文件管理器插入文件
    handleInsertFile(item) {
      if (!this.commentForm.crmfiles) {
        this.commentForm.crmfiles = []
      }

      // 检查是否已存在（优先使用ID，否则使用URL）
      const existingIndex = this.commentForm.crmfiles.findIndex(file =>
        (file.id && item.id && file.id === item.id) ||
        (file.url === item.url)
      )

      if (existingIndex === -1) {
        // 现在后端返回完整的CRMFile对象，直接使用即可
        this.commentForm.crmfiles.push(item)
        this.$message.success(`已添加文件: ${item.filename}`)
      } else {
        this.$message.warning('文件已存在，未重复添加')
      }
    },

    // 下载文件
    downloadFile(item) {
      const link = document.createElement('a')
      link.href = item.url
      link.download = item.filename
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    },

    // 提交评论
    submitComment() {
      if (!this.commentForm.content.trim()) {
        this.$message({
          message: '评论内容不能为空',
          type: 'warning'
        })
        return
      }

      if (!this.internalTicketId && !this.orderId) {
        this.$message({
          message: '请提供工单ID或订单ID',
          type: 'warning'
        })
        return
      }

      this.submitting = true

      // 准备评论数据
      const commentData = {
        content: this.commentForm.content,
        crmfiles: this.commentForm.crmfiles
      }

      // 根据传入的ID类型设置关联对象
      if (this.internalTicketId) {
        commentData.ticket_id = this.internalTicketId
      } else if (this.orderId) {
        commentData.order_id = this.orderId
      }

      PostComment(commentData).then(() => {
        this.submitting = false
        this.$notify({
          title: '成功',
          message: '添加评论成功',
          type: 'success',
          duration: 2000
        })

        // 重置表单
        this.clearForm()

        // 刷新评论列表并设置为最新在前
        this.commentSortOrder = 'newest-first'
        this.fetchComments().then(() => {
          // 滚动到评论列表顶部
          this.$nextTick(() => {
            const commentList = document.querySelector('.comment-list')
            if (commentList) {
              commentList.scrollTop = 0
            }
          })
        })

        // 触发评论添加成功事件
        this.$emit('comment-added')
      }).catch(error => {
        this.submitting = false
        this.$notify({
          title: '失败',
          message: '添加评论失败: ' + (error.message || error),
          type: 'error',
          duration: 2000
        })
      })
    },

    // 清空评论表单
    clearForm() {
      // 清空编辑器内容
      if (this.$refs.editor) {
        try {
          this.$refs.editor.clearContent()
        } catch (e) {
          console.error('清空编辑器内容失败:', e)
          this.commentForm.content = ''
        }
      }
      this.commentForm.content = ''
      this.commentForm.crmfiles = []
      this.fileList = []
      if (this.$refs.commentForm) {
        this.$refs.commentForm.resetFields()
      }
    },

    // 改变评论排序方式
    changeCommentSortOrder(order) {
      this.commentSortOrder = order
    },

    // 获取状态颜色
    getStatusColor(status) {
      const colorMap = {
        'open': '#67C23A',
        'hold': '#E6A23C',
        'close': '#909399'
      }
      return colorMap[status] || '#909399'
    },

    // 处理状态变化
    handleStatusChange(value) {
      if (!this.ticketDetail.id) return

      const tempData = {
        id: this.ticketDetail.id,
        status: value
      }

      // 更新标题显示加载状态
      const originalTitle = this.drawerTitle
      this.drawerTitle = '正在更新状态...'

      // 调用API更新工单状态
      Put(this.ticketDetail.id, tempData).then(() => {
        // 更新本地状态显示
        const statusOption = this.statusOptions.find(item => item.value === value)
        if (statusOption) {
          this.ticketDetail.status_display = statusOption.label
        }

        this.$notify({
          title: '成功',
          message: '工单状态已更新',
          type: 'success',
          duration: 2000
        })

        // 通知父组件刷新列表
        this.$emit('comment-added')
      }).catch((error) => {
        console.error('更新工单状态失败:', error)
        // 如果失败，恢复原来的状态
        this.$notify({
          title: '错误',
          message: '更新工单状态失败',
          type: 'error',
          duration: 2000
        })
      }).finally(() => {
        // 恢复原标题
        this.drawerTitle = originalTitle
      })
    },

    // 新增的刷新评论列表方法
    handleRefreshComments() {
      // 保存原始标题
      const originalTitle = this.drawerTitle
      // 更新标题显示刷新状态
      this.drawerTitle = '正在刷新评论列表...'

      this.loadingComments = true // 设置加载状态
      this.fetchComments().then(() => {
        this.$notify({
          title: '成功',
          message: '评论列表已刷新',
          type: 'success',
          duration: 2000
        })
      }).catch(error => {
        this.$notify({
          title: '错误',
          message: '刷新评论列表失败: ' + (error.message || error),
          type: 'error',
          duration: 2000
        })
      }).finally(() => {
        // 恢复原始标题
        this.drawerTitle = originalTitle
        this.loadingComments = false // 重置加载状态
      })
    },
    // Handle successful ticket creation
    handleTicketCreated(newTicket) {
      this.ticketFormVisible = false // Close the form dialog
      this.handleClose() // Close the comment drawer
      // Optionally emit an event to notify the parent component to refresh its list
      this.$emit('ticket-created', newTicket)
      this.$notify({
        title: '成功',
        message: '新工单已创建',
        type: 'success',
        duration: 2000
      })
    },

    // 新增：打开创建工单表单
    openCreateTicketForm() {
      this.ticketFormVisible = true
    },

    // 新增：打开截止时间对话框
    openDeadlineDialog() {
      // 初始化截止时间为当前工单的截止时间
      this.deadlineForm.end_at = this.ticketDetail.end_at || null
      this.deadlineDialogVisible = true
    },

    // 更新截止时间
    updateDeadline() {
      if (!this.ticketDetail.id) return

      this.submittingDeadline = true

      const tempData = {
        id: this.ticketDetail.id,
        end_at: this.deadlineForm.end_at
      }

      // 更新标题显示加载状态
      const originalTitle = this.drawerTitle
      this.drawerTitle = '正在更新截止时间...'

      // 调用API更新工单截止时间
      Put(this.ticketDetail.id, tempData)
        .then(() => {
          // 更新本地状态显示
          this.ticketDetail.end_at = this.deadlineForm.end_at

          this.$notify({
            title: '成功',
            message: '工单截止时间已更新',
            type: 'success',
            duration: 2000
          })

          // 通知父组件刷新列表
          this.$emit('comment-added')
        })
        .catch((error) => {
          console.error('更新工单截止时间失败:', error)
          this.$notify({
            title: '错误',
            message: '更新工单截止时间失败',
            type: 'error',
            duration: 2000
          })
        })
        .finally(() => {
          // 恢复原标题
          this.drawerTitle = originalTitle
          this.submittingDeadline = false
        })
    },

    // 新增：格式化日期时间
    formatDateTime(dateTime) {
      const date = new Date(dateTime)
      return date.toLocaleString()
    },

    // 打开转发对话框
    openForwardDialog() {
      this.forwardForm = {
        assignee_id: null,
        note: ''
      }
      this.forwardDialogVisible = true

      // 清空之前的用户列表，强制重新加载
      this.usersList = []
      this.getUsersList()
    },

    // 获取员工列表
    getUsersList() {
      if (this.usersList.length > 0) return // 避免重复加载

      this.usersLoading = true
      const params = new URLSearchParams()
      params.append('is_active', 1)
      params.append('pagesize', 50)
      params.append('page', 1)

      GetUsers(null, params.toString()).then(response => {
        this.usersList = response.data.data || []
      }).catch(error => {
        console.error('获取员工列表失败:', error)
        this.$notify({
          title: '错误',
          message: '获取员工列表失败',
          type: 'error',
          duration: 2000
        })
      }).finally(() => {
        this.usersLoading = false
      })
    },

    // 远程搜索用户
    remoteSearchUsers(query) {
      if (query) {
        this.getUsersListWithQuery(query)
      } else {
        this.getUsersList()
      }
    },

    // 根据查询条件获取员工列表
    getUsersListWithQuery(query) {
      this.usersLoading = true
      const params = new URLSearchParams()
      params.append('is_active', 1)
      params.append('pagesize', 20)
      params.append('page', 1)
      if (query) {
        params.append('kw', query)
      }

      GetUsers(null, params.toString()).then(response => {
        this.usersList = response.data.data || []
      }).catch(error => {
        console.error('搜索员工失败:', error)
      }).finally(() => {
        this.usersLoading = false
      })
    },

    // 确认转发工单
    confirmForward() {
      if (!this.forwardForm.assignee_id) {
        this.$message({
          message: '请选择转发的负责人',
          type: 'warning'
        })
        return
      }

      if (this.forwardForm.assignee_id === this.ticketDetail.assignee_id) {
        this.$message({
          message: '不能转发给当前负责人',
          type: 'warning'
        })
        return
      }

      this.submittingForward = true

      // 准备更新数据
      const updateData = {
        id: this.ticketDetail.id,
        assignee_id: this.forwardForm.assignee_id
      }

      // 更新标题显示转发状态
      const originalTitle = this.drawerTitle
      this.drawerTitle = '正在转发工单...'

      // 调用API更新工单负责人
      Put(this.ticketDetail.id, updateData)
        .then(() => {
          // 更新本地状态显示
          const selectedUser = this.usersList.find(user => user.id === this.forwardForm.assignee_id)
          if (selectedUser) {
            this.ticketDetail.assignee_id = this.forwardForm.assignee_id
            this.ticketDetail.assignee_name = selectedUser.name
          }

          // 如果有转发说明，添加一条系统评论
          if (this.forwardForm.note.trim()) {
            const forwardComment = {
              content: `工单已转发给 ${selectedUser ? selectedUser.show_name : ''}。转发说明：${this.forwardForm.note}`,
              ticket_id: this.ticketDetail.id
            }

            PostComment(forwardComment).catch(error => {
              console.error('添加转发评论失败:', error)
            })
          }

          this.$notify({
            title: '成功',
            message: `工单已成功转发给 ${selectedUser ? selectedUser.show_name : ''}`,
            type: 'success',
            duration: 3000
          })

          // 关闭对话框
          this.forwardDialogVisible = false

          // 刷新评论列表
          this.fetchComments()

          // 通知父组件刷新列表
          this.$emit('comment-added')
        })
        .catch(error => {
          console.error('转发工单失败:', error)
          this.$notify({
            title: '错误',
            message: '转发工单失败: ' + (error.message || error),
            type: 'error',
            duration: 2000
          })
        })
        .finally(() => {
          // 恢复原标题
          this.drawerTitle = originalTitle
          this.submittingForward = false
        })
    }
  }
}
</script>

<style scoped>
.ticket-detail-container {
  height: 100%;
  max-height: calc(100vh - 60px);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.ticket-info {
  flex-shrink: 0;
  background-color: #f8f9fa;
  border-radius: 4px;
  padding: 8px 15px;
  border: 1px solid #ebeef5;
  margin: 5px 10px;
}

.ticket-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.ticket-title {
  font-weight: 500;
  font-size: 15px;
  color: #303133;
  flex: 1;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.ticket-actions {
  display: flex;
  align-items: center;
  white-space: nowrap;
  width: 100%;
}

.ticket-meta-item {
  margin-left: 10px;
  font-size: 13px;
  color: #606266;
}

.ticket-description {
  margin-top: 5px;
  white-space: pre-wrap;
  padding: 10px;
  background-color: #fff;
  border-radius: 4px;
  border-left: 3px solid #409EFF;
}

.section-header {
  border-bottom: 2px solid #409EFF;
  padding-bottom: 8px;
  margin-bottom: 20px;
}

h3 {
  margin: 0;
  font-weight: 500;
  font-size: 18px;
  color: #303133;
}

.ticket-comments-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  margin: 0 10px 5px 10px;
  background-color: #fff;
  border-radius: 6px;
  border: 1px solid #ebeef5;
  min-height: 0; /* 允许flex容器收缩 */
  overflow: hidden;
}

.comment-controls {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 15px;
  background-color: #f5f7fa;
  border-radius: 4px 4px 0 0;
  border-bottom: 1px solid #ebeef5;
  font-size: 13px;
  color: #606266;
  flex-shrink: 0;
}

.el-dropdown-link {
  cursor: pointer;
  color: #409EFF;
  font-size: 13px;
}

.comment-count {
  font-weight: 500;
}

.comment-list {
  flex: 1;
  overflow-y: auto;
  background-color: #f5f7fa;
  padding: 10px;
  max-height: 100%; /* 确保不超出父容器 */
}

.comment-item {
  padding: 15px;
  border: 1px solid #ebeef5;
  background-color: #fff;
  margin-bottom: 15px;
  transition: background-color 0.3s;
  border-radius: 6px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  position: relative;
}

.comment-item:hover {
  background-color: #f9fafc;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.comment-item:before {
  content: '';
  position: absolute;
  left: -10px;
  top: 20px;
  width: 0;
  height: 0;
  border-top: 8px solid transparent;
  border-bottom: 8px solid transparent;
  border-right: 10px solid #fff;
  z-index: 1;
}

.system-comment {
  background-color: #f9f9f9;
  border-left: 3px solid #909399;
}

.system-comment:before {
  border-right-color: #f9f9f9;
}

.system-comment .comment-author {
  color: #909399;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12px;
  border-bottom: 1px dashed #ebeef5;
  padding-bottom: 8px;
}

.comment-author {
  font-weight: bold;
  color: #409EFF;
  font-size: 14px;
}

.comment-time {
  color: #909399;
  font-size: 12px;
}

.comment-content {
  margin-bottom: 10px;
  background-color: #fff;
  padding: 12px 0;
  border-radius: 4px;
  line-height: 1.6;
}

/* 添加对内容中图片的样式支持 */
.comment-content >>> img {
  max-width: 100%;
  height: auto;
  border-radius: 4px;
  margin: 8px 0;
  box-shadow: 0 1px 5px rgba(0, 0, 0, 0.1);
}

.comment-content >>> p {
  margin: 0 0 10px 0;
  line-height: 1.6;
}

.comment-content >>> * {
  max-width: 100%;
}

.comment-form {
  flex-shrink: 0;
  margin: 5px 10px 10px 10px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #ebeef5;
  max-height: 320px; /* 增加20px高度 */
  overflow-y: auto; /* 表单内容过多时可滚动 */
}

.compact-form-item {
  margin-bottom: 12px;
}

.compact-form-item:last-child {
  margin-bottom: 0;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding-top: 10px;
  margin-top: 10px;
  border-top: 1px solid #ebeef5;
  background-color: #f8f9fa;
}

.no-comments {
  text-align: center;
  padding: 30px 0;
  color: #909399;
  background-color: #fff;
  border-radius: 4px;
  margin: 15px 0;
}

.no-comments i {
  font-size: 36px;
  margin-bottom: 10px;
}

/* 文件列表样式 */
.file-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 15px;
  background-color: #fff;
  padding: 10px;
  border-radius: 4px;
}

.file-list-compact {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
  margin-bottom: 8px;
}

.file-item-compact {
  display: inline-flex;
  align-items: center;
  background-color: #f0f9ff;
  padding: 2px 8px;
  border-radius: 4px;
  border: 1px solid #d9ecff;
  font-size: 12px;
}

.file-name-compact {
  max-width: 150px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.file-item-compact .el-icon-close {
  margin-left: 5px;
  cursor: pointer;
  color: #909399;
}

.file-item-compact .el-icon-close:hover {
  color: #F56C6C;
}

.file-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100px;
  background-color: #f9f9f9;
  padding: 8px;
  border-radius: 4px;
  transition: all 0.3s;
}

.file-item:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.file-icon {
  height: 60px;
  width: 60px;
}

.file-name {
  margin-top: 5px;
  text-align: center;
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-size: 12px;
}

.file-item a {
  cursor: pointer;
  transition: transform 0.2s;
}

.file-item a:hover {
  transform: scale(1.1);
}

.editor-upload-btn {
  margin-top: 5px;
}

#editorContainer {
  position: relative;
  z-index: 1;
}

/* 抽屉组件自定义样式 */
.ticket-comment-drawer >>> .el-drawer__header {
  margin-bottom: 0;
  padding: 10px 15px;
  font-size: 16px;
  font-weight: bold;
  border-bottom: 1px solid #e4e7ed;
  background-color: #f5f7fa;
}

.ticket-comment-drawer >>> .el-drawer__body {
  overflow: hidden; /* 禁止抽屉body滚动 */
  padding: 0;
  height: calc(100vh - 60px); /* 减去header高度 */
}

/* Tiptap 编辑器样式 */
.comment-form >>> .tiptap-editor {
  margin-bottom: 8px;
}

.comment-form >>> .tiptap-content {
  min-height: 80px !important;
  max-height: 120px;
  overflow-y: auto;
}

/* 提高编辑器层级，防止被抽屉遮挡 */
#editorContainer {
  position: relative;
  z-index: 1;
}

.status-select {
  width: 90px;
  margin-right: 5px;
}

/* 自定义状态选择框样式 */
.ticket-info >>> .el-select .el-input__inner {
  border-color: transparent;
  background-color: rgba(0, 0, 0, 0.05);
  padding: 0 10px;
  height: 28px;
  line-height: 28px;
}

.ticket-info >>> .el-select.open-status .el-input__inner {
  background-color: rgba(103, 194, 58, 0.1);
  color: #67C23A;
  border-left: 3px solid #67C23A;
}

.ticket-info >>> .el-select.hold-status .el-input__inner {
  background-color: rgba(230, 162, 60, 0.1);
  color: #E6A23C;
  border-left: 3px solid #E6A23C;
}

.ticket-info >>> .el-select.close-status .el-input__inner {
  background-color: rgba(144, 147, 153, 0.1);
  color: #909399;
  border-left: 3px solid #909399;
}

/* 添加对 CrmTicketForm 的引用 */
.ticket-comment-drawer {
  position: relative; /* Ensure context for absolute positioning if needed */
}

/* 添加历史工单按钮样式 */
.history-tickets-btn {
  margin-left: 10px;
  font-weight: bold;
  color: #409EFF;
}

/* 创建工单按钮样式 */
.create-ticket-btn {
  margin-left: auto;
}

/* 设置截止时间图标样式 */
.set-deadline-icon {
  margin-left: 5px;
  color: #409EFF;
  cursor: pointer;
  transition: color 0.3s;
}

.set-deadline-icon:hover {
  color: #66b1ff;
}

/* 设置操作区域样式，确保按钮靠右显示 */
.ticket-actions {
  display: flex;
  align-items: center;
  white-space: nowrap;
  width: 100%;
}

/* 转发按钮样式 */
.forward-ticket-btn {
  margin-left: 10px;
  color: #E6A23C;
  font-weight: bold;
}

.forward-ticket-btn:hover {
  color: #D3761A;
}

/* 转发对话框信息样式 */
.forward-info {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 20px;
  border-left: 4px solid #409EFF;
}

.forward-info p {
  margin: 8px 0;
  color: #606266;
}

.forward-info strong {
  color: #303133;
}

/* 附件表单项样式 */
.attachment-form-item {
  position: relative;
}

.attachment-form-item >>> .el-form-item__label {
  position: relative;
}

.attachment-content {
  position: relative;
}

.upload-button-container {
  position: absolute;
  top: -20px;
  left: 45px;
  z-index: 10;
}
</style>
